package com.nageoffer.jobtrain.projects.handler;

import com.nageoffer.jobtrain.common.toolkit.utils.JWTUtils;
import com.nageoffer.jobtrain.common.web.exception.ClientException;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket 通知消息处理器
 */
@Component
public class ContestNotifyWebSocketHandler extends TextWebSocketHandler {
    // 用于存储用户与 WebSocketSession 的映射
    private static final ConcurrentHashMap<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = extractAndValidateToken(session);
        sessionMap.put(username, session);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 可以实现消息的接收处理逻辑
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String username = extractAndValidateToken(session);
        sessionMap.remove(username);
    }

    // 推送消息给指定用户
    public void sendMessage(String username, String message) {
        WebSocketSession session = sessionMap.get(username);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (Throwable ex) {
                throw new ClientException("竞赛通知消息推送异常：" + ex);
            }
        }
    }

    private String extractAndValidateToken(WebSocketSession session) throws Exception {
        String query = session.getUri().getQuery(); // 获取 URL 查询参数
        String token = null;
        // 从查询参数中提取 token
        if (query != null) {
            for (String param : query.split("&")) {
                String[] pair = param.split("=");
                if (pair.length == 2 && "token".equals(pair[0])) {
                    token = pair[1];
                    break;
                }
            }
        }
        // 验证 token 是否为空
        if (token == null || token.isEmpty()) {
            session.close(CloseStatus.NOT_ACCEPTABLE.withReason("非法token"));
            throw new ClientException("非法token");
        }
        return JWTUtils.verifyAndGetUser(token).getUsername();
    }
}
